package 动态访问和修改私有字段;

import java.lang.reflect.Field;

class EmployeePrivate
{
    private String name;
    private double salary;

    public EmployeePrivate(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "EmployeePrivate{name='" + name + "', salary=" + salary + "}";
    }
}

public class AccessPrivateFields {
    public static void main(String[] args) throws Exception {
        EmployeePrivate emp = new EmployeePrivate("John Doe", 50000.0);
        System.out.println("Before modification: " + emp);
        
        // 获取Class对象
        Class<?> clazz = emp.getClass();
        
        // 获取私有字段并设置可访问
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(emp, "Jane Smith");
        
        Field salaryField = clazz.getDeclaredField("salary");
        salaryField.setAccessible(true);
        salaryField.set(emp, 60000.0);
        
        System.out.println("After modification: " + emp);
    }
}